package com.yj.lottery_system.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Configuration
public class RedisUtil {
    //将被存储的数据直接存储，可读
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private final static Logger LOGGER = LoggerFactory.getLogger(RedisUtil.class);

    /**
     * 针对String设置值
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, String value) {
        try {
            stringRedisTemplate.opsForValue().set(key,value);
            return true;
        } catch (Exception e) {
            LOGGER.error("Redis Error set({}, {})",key,value,e);
            return false;
        }
    }

    /**
     * 针对String设置值 有过期时间
     * @param key
     * @param value
     * @param time 过期时间 单位：秒
     * @return
     */
    public boolean set(String key, String value,Long time) {
        try {
            stringRedisTemplate.opsForValue().set(key,value,time, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            LOGGER.error("Redis Error set({}, {}, {})",key,value,time,e);
            return false;
        }
    }
    /**
     * 针对String 获取值
     * @param key
     * @return
     */
    public String get(String key) {
        if(!StringUtils.hasText(key)) {
            return null;
        }
        try {
            String s = stringRedisTemplate.opsForValue().get(key);
            return s;
        } catch (Exception e) {
            LOGGER.error("Redis Error get({})",key,e);
            return null;
        }
    }
    /**
     * 删除值
     * @param key
     * @return
     */
    public boolean del(String... key) {
        try {
            if(null != key && key.length > 0) {
                if(1 == key.length) {
                    stringRedisTemplate.delete(key[0]);
                } else {
                    stringRedisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
                }
            }
            return true;
        } catch (Exception e) {
            LOGGER.error("Redis Error del({})",key,e);
            return false;
        }
    }

    /**
     *
     * @param key
     * @return
     */
    public boolean hasKey(String key) {
        try{
            return StringUtils.hasText(key) ? stringRedisTemplate.hasKey(key) : false;
        }catch (Exception e) {
            LOGGER.error("Redis Error hasKey({})",key,e);
            return false;
        }

    }


}
